<template>
  <view>
    <view class="PolicySearch">
      <view class="PolicySearchc">
        <input
          type="text"
          placeholder="输入关键词查询政策信息"
          v-model="searchKeyword"
          @confirm="searchPolicy"
        />
        <view class="PolocyBtn" @click="searchPolicy">搜索</view>
      </view>
    </view>
    <selectFilter
      ref="selectFilter"
      @changeFilterEvent="changeFilterEvent"
      @changeSelectEvent="handleSelectEvent"
      @changeAddress="changeAddress"
      @clearFilter="clearSelectFilter"
      :tabsList="this.tabsList"
      :total="this.total"
      :selectList="this.selectList"
    />
    <view class="PolicyListx">
      <view
        class="PolicyLi"
        v-for="item in policyList"
        :key="item.id"
        @click="goToGuideDetails(item)"
      >
        <view class="PolicyLis">
          <view class="PolicyLisr">{{ item.policyName }}</view>
        </view>
        <view class="PolicyLic">
          <view class="PolicyLicList on">{{
            getDictLabel(item.policyLevel, this.policyLevel)
          }}</view>
          <view class="PolicyLicList">{{
            getDictLabel(item.policyType, this.policyType)
          }}</view>
          <view class="PolicyLicList">{{
            getDictLabel(item.industryType, this.industryType)
          }}</view>
          <view
            class="PolicyLicList"
            v-if="item.isDeclare == 1"
            style="color: #ffffff; background: #44d6da"
            >申报指南</view
          >
        </view>
        <view class="PolicyLix">
          <view class="PolicyLixl">{{ item.policyPubdept }}</view>
          <view class="PolicyLixr">{{ item.pubTime }}</view>
        </view>
      </view>
      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="loading">
        <view class="loading-text">加载中...</view>
      </view>
      <view class="no-more" v-if="noMore">
        <view class="no-more-text">没有更多数据了</view>
      </view>
    </view>
    <customTabbar :currentPages="1" @tabChange="tabChange"/>
    <filterDialog ref="filter" :types="types" @changeTypes="handleChangeEvent" />
  </view>
</template>

<script>
import customTabbar from "@/pages/components/custom-tabbar.vue";
import filterDialog from "@/pages/components/filter.vue";
import selectFilter from "@/pages/components/selectFilter.vue";
import { getPolicy } from "../../api/api.js";
import { useStore } from 'vuex';
import { DICT_TYPES } from '@/store/modules/dict';
import { getDictLabel } from '@/utils/dict';
// const externalScript = require('../../api/api.js');

export default {
  components: {
    customTabbar,
    filterDialog,
    selectFilter,
  },
  data() {
    return {
      types: false,
      page: 1,
      limit: 5,
      total: 0,
      policyList: [],
      loading: false,
      noMore: false,
      searchKeyword: "",

      policyLevel: [],
      policyType: [],
      industryType: [],

      tabsList: [
        { title: "政策层级", selectValue: -1, field: "policyLevel" },
        { title: "政策类型", selectValue: -1, field: "policyType" },
      ],
      selectList: [],
      industryTypeValue: -1,
      timeRange: [],

      address: "",
    };
  },
  onLoad() {
    console.log("created");
    this.init();
    this.getDictData();
  },
  methods: {
    tabChange(){
      console.log("政策智库")
      this.$refs.filter.clear();
      this.industryTypeValue = -1;
      this.timeRange = [];
      this.$refs.selectFilter.clearFilter();
    },
    getDictLabel,
    //清除左边所有筛选
    clearSelectFilter(){
      this.address = "";
      this.searchKeyword = "";
      this.tabsList.forEach((item) => {
        item.selectValue = -1;
      });
      this.init();
    },

    changeAddress(param) {
      console.log(param);
      this.address = param;
      this.page = 1;
      this.getPolicyList(this.page);
    },

    handleChangeEvent(industryTypeValue, timeRange) {
      this.types = false;

      this.industryTypeValue = industryTypeValue;
      this.timeRange = timeRange;
      console.log(this.industryTypeValue);
      console.log(this.timeRange);

      this.page = 1;
      this.getPolicyList(this.page);
    },

    handleSelectEvent() {
      console.log("item是", this.tabsList);
      this.page = 1;
      this.getPolicyList(this.page);
    },

    //查询字典数据
    async getDictData() {
      const store = useStore();
      
      // 加载政策层级
      this.policyLevel = await store.dispatch('dict/loadDict', DICT_TYPES.POLICY_LEVEL);
      
      // 加载行业分类
      this.industryType = await store.dispatch('dict/loadDict', DICT_TYPES.INDUSTRY_TYPE);
      
      // 加载政策类型
      this.policyType = await store.dispatch('dict/loadDict', DICT_TYPES.POLICY_TYPE);
      
      // 准备下拉选择数据
      this.selectList = [
        store.getters['dict/getDictWithAll'](DICT_TYPES.POLICY_LEVEL),
        store.getters['dict/getDictWithAll'](DICT_TYPES.POLICY_TYPE)
      ];
    },

    changeFilterEvent() {
      this.types = true;
    },
    // 获取政策列表数据
    async getPolicyList(page, isLoadMore = false) {
      try {
        this.loading = true;
        let param = "page=" + page + "&limit=" + this.limit;

        // 如果有搜索关键词，添加到请求URL中
        if (this.searchKeyword && this.searchKeyword.trim() !== "") {
          param +=
            "&policyName=" + encodeURIComponent(this.searchKeyword.trim());
        }

        this.tabsList.forEach((item) => {
          if (item.selectValue != -1) {
            param += "&" + item.field + "=" + item.selectValue;
          }
        });

        if (this.industryTypeValue != -1) {
          param += "&industryType=" + this.industryTypeValue;
        }

        if (this.address != "") {
          param += "&policyRegion=" + encodeURIComponent(this.address);
        }

        if (this.timeRange.length == 2) {
          param += "&pubTime=" + this.timeRange[0] + "," + this.timeRange[1];
        }

        const res = await getPolicy(param);

        if (res.code === 0) {
          const { list = [], total = 0 } = res.data;

          if (isLoadMore) {
            // 加载更多模式，追加数据
            if (list.length > 0) {
              this.policyList = [...this.policyList, ...list];
            }
          } else {
            // 初始化模式，替换数据
            this.policyList = list;
          }

          this.total = total;

          // 判断是否还有更多数据
          this.noMore = this.policyList.length >= total;
        } else {
          throw new Error(res.msg || "获取数据失败");
        }
      } catch (error) {
        console.error("获取政策列表失败:", error);
        uni.showToast({
          title: error.message || "获取数据失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    // 重置并初始化数据
    async init() {
      // 重置所有状态
      this.resetState();
      // 调用获取政策列表方法
      await this.getPolicyList(this.page);
    },

    // 重置状态
    resetState() {
      this.page = 1;
      this.noMore = false;
      this.policyList = [];
      this.total = 0;
    },

    // 加载更多数据
    async loadMore() {
      // 如果正在加载或没有更多数据，直接返回
      if (this.loading || this.noMore) return;

      // 如果已加载的数据量达到或超过总数，不再加载
      if (this.policyList.length >= this.total) {
        this.noMore = true;
        return;
      }

      this.page++;
      // 调用获取政策列表方法，并标记为加载更多模式
      await this.getPolicyList(this.page, true);
    },

    // 处理筛选事件
    async handleSelectEvent() {
      console.log("item是", this.tabsList);
      // 重置状态
      this.resetState();
      // 重新加载数据
      await this.getPolicyList(this.page);
    },

    // 搜索政策
    async searchPolicy() {
      // 重置状态
      this.resetState();
      // 调用获取政策列表方法
      await this.getPolicyList(this.page);
    },

    goToGuideDetails(item) {
      uni.navigateTo({
        url: `/pages/policyDetails/index?id=${item.id}&flag=1`,
      });
    },
  },
  onReachBottom() {
    this.loadMore();
  },
};
</script>

<style lang="scss">
page {
  background: #f7f8fc;
}

.PolicyListx {
  width: 100%;
  padding: 0 24rpx 130rpx;
  box-sizing: border-box;

  .PolicyLi {
    padding: 30rpx 32rpx 15rpx;
    background: #ffffff;
    border-radius: 10rpx;
    margin: 0 0 29rpx;

    .PolicyLis {
      padding: 0 0 20rpx;

      .PolicyLisl {
        float: left;
        height: 40rpx;
        line-height: 40rpx;
        padding: 0 11rpx;
        font-size: 24rpx;
        color: #4e5262;
        background: #ecf3fc;
        border-radius: 5rpx;
        margin-right: 17rpx;
        margin-top: 3rpx;
      }

      .PolicyLisr {
        font-size: 32rpx;
        color: #202020;
        line-height: 44rpx;
      }
    }

    .PolicyLic {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      padding: 0 0 19rpx;
      border-bottom: 1px solid #f1f1f1;
      .PolicyLicList {
        height: 40rpx;
        line-height: 40rpx;
        padding: 0 11rpx;
        border-radius: 10rpx;
        background: #ecf3fc;
        margin-right: 20rpx;
        font-size: 24rpx;
        color: #4e5262;
        margin-bottom: 11rpx;
        &.on {
          color: #ffffff;
          padding: 0 18rpx;
          background: url("/static/images/policybj.png") no-repeat center / 100%
            100%;
        }
      }
    }
    .PolicyLix {
      display: flex;
      align-items: center;
      padding: 20rpx 0 10rpx;
      justify-content: space-between;
      .PolicyLixl {
        font-size: 28rpx;
        color: #4e5262;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 20rpx;
        max-width: 70%;
      }
      .PolicyLixr {
        font-size: 26rpx;
        color: #4e5262;
        font-family: "Arial";
        flex-shrink: 0;
        line-height: 40rpx;
      }
    }
  }
}
.ZheZhao {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 98;
  background: rgba(0, 0, 0, 0.5);
}
.DiaLogShai {
  position: fixed;
  right: 0;
  top: 0;
  width: 660rpx;
  height: 100%;
  box-sizing: border-box;
  background: #f7f8fc;
  z-index: 99;
  border-radius: 30rpx 0 0 0;
  .DiaLogShais {
    height: calc(100% - 160rpx);
    overflow-y: auto;
    .DiaLogShaisFaBu {
      padding: 0 40rpx 40rpx;
      margin-bottom: 30rpx;
      border-radius: 30rpx;
      background: #ffffff;
    }
    .DiaLogTitle {
      height: 86rpx;
      line-height: 86rpx;
      padding: 10rpx 0 0;
      font-size: 28rpx;
      color: #202020;
    }
    .DiaLogShaisFenLei {
      padding: 0 40rpx 20rpx;
      margin-bottom: 30rpx;
      border-radius: 30rpx;
      background: #ffffff;
      .DiaLogShaiList {
        overflow: hidden;
        .DiaLogShaiLi {
          float: left;
          height: 50rpx;
          line-height: 50rpx;
          padding: 0 11rpx;
          background: #f9f9f9;
          border: 2rpx solid #f9f9f9;
          border-radius: 10rpx;
          margin-right: 20rpx;
          margin-bottom: 20rpx;
          font-size: 28rpx;
          color: #202020;
          &.on {
            color: #2f59fe;
            background: #edf4fd;
            border-color: #2f59fe;
          }
        }
      }
    }
  }
  .DiaLogShaix {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    height: 160rpx;
    .DiaLogShaiReset {
      display: inline;
      width: 280rpx;
      height: 80rpx;
      line-height: 78rpx;
      font-size: 32rpx;
      color: #202020;
      border: 1rpx solid #cfd2d7;
      box-sizing: border-box;
      margin: 0 10rpx;
      border-radius: 10rpx;
    }
    .DiaLogShaiSubmit {
      display: inline;
      width: 280rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 32rpx;
      color: #ffffff;
      background: #2f59fe;
      margin: 0 10rpx;
      border-radius: 10rpx;
    }
  }
}

/* 加载更多和没有更多数据的样式 */
.loading-more,
.no-more {
  text-align: center;
  padding: 20rpx 0;

  .loading-text,
  .no-more-text {
    font-size: 28rpx;
    color: #999;
    line-height: 40rpx;
  }
}

.loading-more {
  .loading-text::before {
    content: "";
    display: inline-block;
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;
    border: 2rpx solid #999;
    border-top-color: transparent;
    border-radius: 50%;
    vertical-align: middle;
    animation: loading 0.8s linear infinite;
  }
}

@keyframes loading {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>